<?php
/**
 * 公用控制器,直接继承Controller
 * 公用：图片上传、省市区处理、文件上传及非业务性逻辑
 * @author: yanxs <541139655@qq.com>
 * @version: 1.0
 * @date: 2021/3/22
 */

namespace App\Http\Controllers;


use App\Repositories\PrtAreasRepository;
use Illuminate\Http\Request;

class ShareController extends Controller
{
    protected $areas;
    protected $region;
    protected $suffix = ['jpg','jpeg','gif','png'];
    public function __construct(PrtAreasRepository $region)
    {
        $this->region = $region;
    }

    //图片上传处理
    public function upload(Request $request)
    {
        $file=$request->file('file');

        //获取后缀
        $ext = $file->getClientOriginalExtension();

        //生成文件名称
        $filename = time() . uniqid() . "." . $ext;

        //文件保存路径
        $date = date('Ymd');
        $filepath = config('common.image_path').$date;
        if (!file_exists($filepath)) {
            @mkdir($filepath);
        }
        $res = $file->move($filepath,$filename);
        return response()->json(['status' => 200, 'success' => 'true', 'data' => config('common.static_url').'/'.$date.'/'.$filename]);
    }
    //编辑器图片上传
    public function editorUpload(Request $request)
    {
        //$type = $request->input('type');
        $files = $request->file();
        $list = [];
        $files = array_values($files);
        foreach ($files as $k => $file) {
            $ext = $file->getClientOriginalExtension();
            $filename = time() . uniqid() . "." . $ext;
            $date = date('Ymd');
            $filepath = config('common.image_path').$date;
            if (!file_exists($filepath)) {
                @mkdir($filepath);
            }
            $res = $file->move($filepath,$filename);
            $list[$k]['url'] = config('common.static_url').'/'.$date.'/'.$filename;
            $list[$k]['alt'] = '';
            $list[$k]['href'] = '';
        }
        return response()->json(['errno'=>0,'data' => $list]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function fileUpload(Request $request)
    {
        $file=$request->file('file');

        //获取后缀
        $ext = $file->getClientOriginalExtension();
        $fileName = $file->getClientOriginalName();

        //文件保存路径
        $filepath = config('common.upload_file_path')."file";
        if (!file_exists($filepath)) {
            @mkdir($filepath);
        }
        $res = $file->move($filepath,$fileName);
        return response()->json(['status' => 200, 'success' => 'true','data'=>$filepath.$fileName]);
    }

    /**
     * 请求地址库数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function areas(Request $request)
    {
        $id = $request->post("id");
        $list = $this->region->getAreasLists($id);
        return response()->json(['status' => 200, 'list' => $list]);
    }
}
